import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Divider, Table, message as msg, Modal} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS} from '../constants';
import SelectAlert from '../common/SelectAlert';
import {computeSelectedRows} from './utils';
import {conventSorter, formatAmount} from '../utils';
import styles from './style.css';
import {getSaleOrdersDetails} from './api';
import {unionBy, union} from 'lodash';
const MultiSelectAlert = SelectAlert.Multi;

class SaleOrderDetailPanel extends PureComponent {
    state = {
        isFetching: false,
        data: {},
        details: [],
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        selectedRowKeys: [],
        selectedRows: [],
    }
    componentDidMount() {
        const condition = {
            id: this.props.saleOrderId,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: pagination.current - 1
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }

    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }

    onQuery = condition => {
        this.setState({isFetching: true});
        getSaleOrdersDetails(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        details: res.data.details,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChangeRadio = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows
        });
    }

    onCloseTag = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }

    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'saleOrderDetailPanel.validate.detail',
                defaultMessage: '请选择订单清单'
            }));
        const groupByRows = unionBy(union(this.state.selectedRows, this.props.currentSelectRowkeys),
            'currency', 'tradeMethodId', 'salesOrderPriceTerms', 'paymentType', 'transportType');
        if(groupByRows.length > 1)
            return msg.warn(this.props.intl.formatMessage({
                id: 'CBUSelectPanel.validate.groupByRows',
                defaultMessage: '只有相同品牌、总代、币种、贸易方式、付款方式、价格条款、运输方式的销售订单才能合并'
            }));
        this.props.onSelect(this.state.selectedRows);
    }
    
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'saleOrderDetailPanel.column.sourceCode',
                    defaultMessage: '源单据编号'
                }),
                dataIndex: 'sourceCode'
            }, {
                title: formatMessage({
                    id: 'saleOrderDetailPanel.column.kdBomCode',
                    defaultMessage: 'KDBOM号'
                }),
                dataIndex: 'kdBomCode'
            }, {
                title: formatMessage({
                    id: 'saleOrderDetailPanel.column.descriptionOfGoods',
                    defaultMessage: '产品描述'
                }),
                dataIndex: 'descriptionOfGoods'
            }, {
                title: formatMessage({
                    id: 'saleOrderDetailPanel.column.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity'
            }, {
                title: formatMessage({
                    id: 'saleOrderDetailPanel.column.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'saleOrderDetailPanel.column.taxFreePrice',
                    defaultMessage: '不含税单价'
                }),
                dataIndex: 'taxFreePrice',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'saleOrderDetailPanel.column.totalPrice',
                    defaultMessage: '总价'
                }),
                dataIndex: 'totalPrice',
                render: text => formatAmount(text)
            }, {
                title: formatMessage({
                    id: 'saleOrderDetailPanel.column.taxFreeTotalPrice',
                    defaultMessage: '不含税总价'
                }),
                dataIndex: 'taxFreeTotalPrice',
                render: text => formatAmount(text)
            }
        ];
            

        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            },
            getCheckboxProps: record => ({
                disabled: this.props.currentSelectRowkeys.some(item => item.saleOrderDetailId === record.id)
            })
        };
        return (
            <Modal
                title={formatMessage({
                    id: 'saleOrderDetailPanel.show.query',
                    defaultMessage: '销售订单清单查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Divider className={styles.divider}/>
                <MultiSelectAlert data={this.state.selectedRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}
                    onDeleteAll={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={this.state.details}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}/>
            </Modal >
        );
    }
}

SaleOrderDetailPanel.propTypes = {
    currentSelectRowkeys: PropTypes.array.isRequired,
    onSelect: PropTypes.func.isRequired,
    brandId: PropTypes.string,
    dealerId: PropTypes.string,
    intl: PropTypes.object,
    partOrderTypeId: PropTypes.string,
    transportType: PropTypes.number,
    onCancel: PropTypes.func,
};
import {injectIntl} from './intl';

export default injectIntl(SaleOrderDetailPanel);
